package com.ITXu.reggie.controller;

import java.time.LocalDateTime;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.ITXu.reggie.commom.R;
import com.ITXu.reggie.entity.Employee;
import com.ITXu.reggie.service.EmployeeService;
import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
@CrossOrigin
@RequestMapping("/employee")
public class EmployeeController {
	
	@Autowired
	private EmployeeService employeeService;
    
	/*
	 1. 将页面提交的密码进行加密
	 2. 根据页面提交的username查询数据库，未查询到返回查询失败
	 3. 对比页面提交的password
	 4. 查看员工状态，若被禁用则返回被禁用结果
	 5. 登陆成功，将员工id录入session并返回登陆成功结果
	 */
	
	/**
	 * 
	 * @param request
	 * @param employee
	 * @return
	 */
	@PostMapping("/login")
	public R<Employee> Login(HttpServletRequest request, @RequestBody Employee employee){
		//以下逻辑可写在业务层service中
		String password = DigestUtils.md5DigestAsHex(employee.getPassword().getBytes());
		//查询条件构造器
		LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
		//设置查询条件（eq中前者为lambda表达式，表示Employee实体类中的任意对象的getUsername方法与前端传入的username的等价比较）
		queryWrapper.eq(Employee::getUsername, employee.getUsername());
		//调用service层
		Employee emp = employeeService.getOne(queryWrapper);
		if(emp == null) {
			return R.error("用户名错误，登陆失败");
		}
		if(!emp.getPassword().equals(password)) {
			return R.error("密码错误，登陆失败");
		}
		if (emp.getStatus() == 0) {
			return R.error("账号已禁用");
		}
		emp.setPassword(" ");
		request.getSession().setAttribute("employee", emp.getId());
		return R.success(emp);
	};
	
	@PostMapping("/logout")
	public R<String> Logout(HttpServletRequest request){
		//退出前先删除当前会话的session
		request.getSession().removeAttribute("employee");
		return R.success("退出成功");
	}
	
	@PostMapping
	public R<String> save(HttpServletRequest request, @RequestBody Employee emp){
		log.info("新增员工，员工信息：{}", emp.toString());
		emp.setPassword("123456");
		//设置创建时间和更新时间
		//emp.setCreateTime(LocalDateTime.now());
		//emp.setUpdateTime(LocalDateTime.now());
		//获取登陆人id
		//Long empId = (Long)request.getSession().getAttribute("employee");
		//用empId作为createUser和updateUser
		//emp.setCreateUser(empId);
		//emp.setUpdateUser(empId);
		//调用service层
		employeeService.save(emp);
		return R.success("新增员工成功");
	}
	
	@GetMapping("/page")
	public R<Page> page(int page, int pageSize, String name){
		log.info("page:{}, pageSize:{}, name:{}", page, pageSize, name);
		//构造分页构造器**引入分页构造器需要先在config文件夹下配置mybatisPlusInterceptor，再在mybatisPlusInterceptor中添加PaginationInnerInterceptor对象
		Page pageInfo = new Page<>();
		//构造条件构造器**mybatisplus的查询模式：Iservice方法+条件构造器
		LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
		//添加查询条件
		queryWrapper.like(org.apache.commons.lang.StringUtils.isNotEmpty(name), Employee::getName, name);
		//添加排序条件
		queryWrapper.orderByDesc(Employee::getUpdateTime);
		//执行查询
		employeeService.page(pageInfo, queryWrapper);
		return R.success(pageInfo);
	}
	
	@PutMapping
	public R<String> update(HttpServletRequest request, @RequestBody Employee employee){
		employeeService.updateById(employee);
		//设置更新时间
		//employee.setUpdateTime(LocalDateTime.now());
		//获取登陆人id
		//Long empId = (Long)request.getSession().getAttribute("employee");
		//设置更新人
		//employee.setUpdateUser(empId);
		return R.success("状态更新成功");
	}
	
	@GetMapping("/{id}")
	public R<Employee> getById(@PathVariable Long id){
		Employee employee = employeeService.getById(id);
		if (employee != null) {
			return R.success(employee);
		}
		return R.error("未查找到相应员工");
	}
}
